import React, { useState } from 'react';
import {
  View,
  StyleSheet,
  TouchableOpacity,
  Image,
  Platform,
  Dimensions,
  StatusBar,
  ActivityIndicator,
  Alert,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/Ionicons';
import AntDesign from 'react-native-vector-icons/AntDesign';
import { WebView } from 'react-native-webview';
import {
  ResponsiveContainer,
  ResponsiveText,
  scale,
} from '../components';

// 示例订单信息
const orderData = {
  id: 'XM12345678',
  rider: {
    name: '李小小',
    rating: 4.7,
    phone: '138****1234',
    avatar: 'https://cdn.pixabay.com/photo/2016/08/08/09/17/avatar-1577909_960_720.png',
  },
  items: [
    { id: 1, name: '胡萝卜', image: 'https://cdn.pixabay.com/photo/2015/03/14/14/00/carrots-673184_960_720.jpg', price: 36.8 },
    { id: 2, name: '橘子', image: 'https://cdn.pixabay.com/photo/2017/01/20/15/06/oranges-1995056_960_720.jpg', price: 39.8 },
  ],
  totalPrice: 76.6,
  estimatedArrival: '15分钟',
  distance: '1.2公里',
  status: '配送中',
};

// 高德地图API密钥（需要替换为你自己的）
const AMAP_KEY = '0de291b5267102b7c92fb054cfdad272';

// 骑手当前位置（示例）
const riderPosition = {
  latitude: 31.233416,
  longitude: 121.478701,
};

// 目的地坐标（示例）
const destinationPosition = {
  latitude: 31.235416,
  longitude: 121.483701,
};

const OrderTrackingScreen: React.FC = () => {
  const navigation = useNavigation();
  const [loading, setLoading] = useState(true);
  const mapHeight = Dimensions.get('window').height * 0.5;

  // 创建地图HTML
  const createMapHTML = () => {
    return `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
        <title>高德地图骑手跟踪</title>
        <style>
          body, html { height: 100%; margin: 0; padding: 0; }
          #container { width: 100%; height: 100%; }
          .amap-logo, .amap-copyright { display: none; }
        </style>
        <script type="text/javascript">
          window.onerror = function(message, source, lineno, colno, error) {
            document.getElementById('container').innerHTML = '地图加载失败: ' + message;
            return true;
          };
        </script>
        <script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=${AMAP_KEY}&plugin=AMap.Scale,AMap.ToolBar,AMap.PlaceSearch"></script>
      </head>
      <body>
        <div id="container"></div>
        <script>
          try {
            // 初始化地图
            const map = new AMap.Map('container', {
              zoom: 15,
              center: [${riderPosition.longitude}, ${riderPosition.latitude}],
              viewMode: '2D',
              resizeEnable: true,
              features: ['bg', 'road', 'building', 'point'],
              mapStyle: 'amap://styles/normal',
              showLabel: true,
              showIndoorMap: true,
              showBuilding: true,
              labelzIndex: 120
            });
            
            // 添加基础控件
            map.addControl(new AMap.Scale());
            map.addControl(new AMap.ToolBar());
            
            // 添加路网及兴趣点图层
            AMap.plugin(['AMap.IndoorMap'], function() {
              const layers = [
                new AMap.TileLayer.RoadNet({
                  zIndex: 10
                }),
                new AMap.Buildings({
                  zooms: [14, 20],
                  zIndex: 11,
                  heightFactor: 2
                })
              ];
              map.add(layers);
            });
            
            // 启用交通流量图层
            const traffic = new AMap.TileLayer.Traffic({
              zIndex: 10
            });
            map.add(traffic);
            
            // 自定义骑手标记
            const riderMarker = new AMap.Marker({
              position: [${riderPosition.longitude}, ${riderPosition.latitude}],
              icon: new AMap.Icon({
                size: new AMap.Size(32, 32),
                image: 'https://cdn.pixabay.com/photo/2014/04/03/10/32/person-310807_960_720.png',
                imageSize: new AMap.Size(32, 32)
              }),
              title: '骑手位置',
              offset: new AMap.Pixel(-16, -32)
            });
            
            // 自定义目的地标记
            const destMarker = new AMap.Marker({
              position: [${destinationPosition.longitude}, ${destinationPosition.latitude}],
              icon: new AMap.Icon({
                size: new AMap.Size(40, 40),
                image: 'https://img.icons8.com/color/96/000000/address--v1.png',
                imageSize: new AMap.Size(40, 40)
              }),
              title: '配送目的地',
              offset: new AMap.Pixel(-20, -40)
            });
            
            // 添加骑手信息窗体
            const riderInfoWindow = new AMap.InfoWindow({
              content: '<div style="padding:10px;"><b>骑手位置</b><br/>正在向您配送</div>',
              offset: new AMap.Pixel(0, -30)
            });
            
            // 添加目的地信息窗体
            const destInfoWindow = new AMap.InfoWindow({
              content: '<div style="padding:10px;"><b>配送目的地</b><br/>预计 ${orderData.estimatedArrival} 送达<br/>配送距离: ${orderData.distance}</div>',
              offset: new AMap.Pixel(0, -30)
            });
            
            // 点击标记显示信息窗体
            riderMarker.on('click', () => {
              riderInfoWindow.open(map, riderMarker.getPosition());
            });
            
            destMarker.on('click', () => {
              destInfoWindow.open(map, destMarker.getPosition());
            });
            
            // 添加标记到地图
            map.add([riderMarker, destMarker]);
            
            // 异步获取路线规划
            AMap.plugin('AMap.Driving', function() {
              const driving = new AMap.Driving({
                map: map,
                policy: AMap.DrivingPolicy.LEAST_TIME
              });
              
              driving.search(
                [${riderPosition.longitude}, ${riderPosition.latitude}],
                [${destinationPosition.longitude}, ${destinationPosition.latitude}],
                function(status, result) {
                  if (status === 'complete') {
                    // 获取驾车路线，绘制绿色线路
                    if (result.routes && result.routes.length) {
                      // 清除默认绘制的路线
                      driving.clear();
                      
                      // 自定义绘制路线
                      const path = [];
                      result.routes[0].steps.forEach(step => {
                        step.path.forEach(p => {
                          path.push(p);
                        });
                      });
                      
                      // 使用更明显的路线样式
                      const routeLine = new AMap.Polyline({
                        path: path,
                        strokeColor: '#4CAF50',
                        strokeWeight: 8,
                        strokeOpacity: 0.8,
                        showDir: true,
                        lineJoin: 'round',
                        lineCap: 'round',
                        dirColor: '#ff8800',
                        isOutline: true,
                        outlineColor: '#ffffff',
                        borderWeight: 2
                      });
                      
                      map.add(routeLine);
                      
                      // 在路线起点和终点之间添加方向箭头
                      const pathNavigator = new AMap.PathNavigator({
                        path: path,
                        speed: 1000,
                        range: [0, 1],
                        getPosition: (pathData, rangeIndex) => {
                          return pathData[Math.floor(pathData.length * rangeIndex)];
                        },
                        autoRotation: true,
                        directionMarkerStyle: {
                          width: 12,
                          height: 12,
                          content: '<div style="background-color:#ff8800;border-radius:50%;width:100%;height:100%"></div>'
                        },
                        stallMarkerStyle: {
                          width: 12,
                          height: 12,
                          content: '<div style="background-color:#ffffff;border:2px solid #4CAF50;border-radius:50%;width:100%;height:100%"></div>'
                        }
                      });
                      pathNavigator.start();
                    }
                  }
                }
              );
            });
            
            // 在地图上添加骑手到目的地的直线连接
            const straightLine = new AMap.Polyline({
              path: [
                [${riderPosition.longitude}, ${riderPosition.latitude}],
                [${destinationPosition.longitude}, ${destinationPosition.latitude}]
              ],
              strokeColor: '#1976D2',
              strokeWeight: 3,
              strokeOpacity: 0.5,
              strokeStyle: 'dashed',
              strokeDasharray: [5, 5]
            });
            
            map.add(straightLine);
            
            // 适应视图
            map.setFitView();
          } catch (e) {
            document.getElementById('container').innerHTML = '地图加载错误: ' + e.message;
          }
        </script>
      </body>
      </html>
    `;
  };

  // 在地图加载完成后处理
  const onMapLoaded = () => {
    setLoading(false);
  };

  // 联系骑手
  const contactRider = () => {
    Alert.alert('联系骑手', `拨打 ${orderData.rider.phone} 联系骑手`);
  };

  // 联系客服
  const contactService = () => {
    navigation.navigate('ChatScreen' as never);
  };

  const handleBack = () => {
    navigation.goBack();
  };

  return (
    <ResponsiveContainer style={styles.container}>
      <StatusBar backgroundColor="#4CAF50" barStyle="light-content" />
      
      {/* 地图区域 */}
      <View style={[styles.mapContainer, { height: mapHeight }]}>
        {loading && (
          <View style={styles.loadingContainer}>
            <ActivityIndicator size="large" color="#4CAF50" />
            <ResponsiveText style={styles.loadingText}>加载地图中...</ResponsiveText>
          </View>
        )}
        
        <WebView
          source={{ html: createMapHTML() }}
          onLoad={onMapLoaded}
          style={styles.map}
          javaScriptEnabled={true}
          domStorageEnabled={true}
          startInLoadingState={true}
          renderLoading={() => <View />}
          renderError={() => (
            <View style={styles.errorContainer}>
              <ResponsiveText style={styles.errorText}>地图加载失败，请检查网络连接</ResponsiveText>
            </View>
          )}
        />
        
        {/* 返回按钮 */}
        <TouchableOpacity style={styles.backButton} onPress={handleBack}>
          <Icon name="chevron-back" size={scale(22)} color="#333" />
        </TouchableOpacity>
      </View>
      
      {/* 订单信息区域 */}
      <View style={styles.orderInfoContainer}>
        <View style={styles.orderHeader}>
          <ResponsiveText style={styles.orderTitle}>订单跟踪</ResponsiveText>
          <TouchableOpacity style={styles.closeButton} onPress={handleBack}>
            <AntDesign name="close" size={scale(20)} color="#666" />
          </TouchableOpacity>
        </View>
        
        {/* 骑手信息 */}
        <View style={styles.riderInfoContainer}>
          <Image
            source={{ uri: orderData.rider.avatar }}
            style={styles.riderAvatar}
            defaultSource={require('../node_modules/react-native/Libraries/NewAppScreen/components/logo.png')}
          />
          <View style={styles.riderDetails}>
            <ResponsiveText style={styles.riderName}>
              {orderData.rider.name}
            </ResponsiveText>
            <View style={styles.ratingContainer}>
              <AntDesign name="star" size={scale(14)} color="#FFBF00" />
              <ResponsiveText style={styles.ratingText}>
                {orderData.rider.rating}
              </ResponsiveText>
            </View>
          </View>
          <View style={styles.contactButtonsContainer}>
            <TouchableOpacity style={styles.contactButton} onPress={contactRider}>
              <Icon name="call" size={scale(18)} color="#4CAF50" />
            </TouchableOpacity>
            <TouchableOpacity style={styles.contactButton} onPress={contactService}>
              <Icon name="chatbubble-ellipses" size={scale(18)} color="#4CAF50" />
            </TouchableOpacity>
          </View>
        </View>
        
        {/* 配送信息 */}
        <View style={styles.deliveryInfoContainer}>
          <View style={styles.deliveryInfoItem}>
            <Icon name="time-outline" size={scale(16)} color="#4CAF50" />
            <ResponsiveText style={styles.deliveryInfoText}>预计到达: {orderData.estimatedArrival}</ResponsiveText>
          </View>
          <View style={styles.deliveryInfoItem}>
            <Icon name="location-outline" size={scale(16)} color="#4CAF50" />
            <ResponsiveText style={styles.deliveryInfoText}>配送距离: {orderData.distance}</ResponsiveText>
          </View>
        </View>
        
        {/* 订单商品信息 */}
        <View style={styles.orderItemsContainer}>
          {orderData.items.map((item) => (
            <View key={item.id} style={styles.orderItem}>
              <Image 
                source={{ uri: item.image }} 
                style={styles.itemImage}
                defaultSource={require('../node_modules/react-native/Libraries/NewAppScreen/components/logo.png')}
              />
              <View style={styles.itemDetails}>
                <ResponsiveText style={styles.itemName}>{item.name}</ResponsiveText>
              </View>
            </View>
          ))}
          <View style={styles.priceContainer}>
            <ResponsiveText style={styles.priceText}>
              共计: ¥{orderData.totalPrice}
            </ResponsiveText>
          </View>
        </View>
      </View>
    </ResponsiveContainer>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F8F8F8',
  },
  mapContainer: {
    position: 'relative',
    width: '100%',
  },
  map: {
    flex: 1,
  },
  loadingContainer: {
    position: 'absolute',
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(255, 255, 255, 0.7)',
    zIndex: 10,
  },
  loadingText: {
    marginTop: scale(10),
    fontSize: scale(14),
    color: '#4CAF50',
  },
  errorContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: scale(20),
  },
  errorText: {
    fontSize: scale(14),
    color: '#FF5252',
    textAlign: 'center',
  },
  backButton: {
    position: 'absolute',
    top: scale(16),
    left: scale(16),
    width: scale(36),
    height: scale(36),
    borderRadius: scale(18),
    backgroundColor: 'white',
    justifyContent: 'center',
    alignItems: 'center',
    ...Platform.select({
      ios: {
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 1 },
        shadowOpacity: 0.2,
        shadowRadius: 2,
      },
      android: {
        elevation: 2,
      },
    }),
  },
  orderInfoContainer: {
    flex: 1,
    backgroundColor: 'white',
    borderTopLeftRadius: scale(16),
    borderTopRightRadius: scale(16),
    marginTop: scale(-20),
    paddingBottom: Platform.OS === 'ios' ? scale(20) : 0,
    ...Platform.select({
      ios: {
        shadowColor: '#000',
        shadowOffset: { width: 0, height: -2 },
        shadowOpacity: 0.1,
        shadowRadius: 4,
      },
      android: {
        elevation: 4,
      },
    }),
  },
  orderHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: scale(16),
    paddingVertical: scale(12),
    borderBottomWidth: 1,
    borderBottomColor: '#F0F0F0',
  },
  orderTitle: {
    fontSize: scale(16),
    fontWeight: '600',
    color: '#333',
  },
  closeButton: {
    padding: scale(5),
  },
  riderInfoContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: scale(16),
    paddingVertical: scale(16),
    borderBottomWidth: 1,
    borderBottomColor: '#F0F0F0',
  },
  riderAvatar: {
    width: scale(50),
    height: scale(50),
    borderRadius: scale(25),
    backgroundColor: '#F0F0F0',
  },
  riderDetails: {
    flex: 1,
    marginLeft: scale(12),
  },
  riderName: {
    fontSize: scale(16),
    fontWeight: '500',
    color: '#333',
  },
  ratingContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: scale(4),
  },
  ratingText: {
    fontSize: scale(14),
    color: '#666',
    marginLeft: scale(4),
  },
  contactButtonsContainer: {
    flexDirection: 'row',
  },
  contactButton: {
    width: scale(36),
    height: scale(36),
    borderRadius: scale(18),
    backgroundColor: '#F0F0F0',
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: scale(8),
  },
  orderItemsContainer: {
    padding: scale(16),
  },
  orderItem: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: scale(12),
  },
  itemImage: {
    width: scale(40),
    height: scale(40),
    borderRadius: scale(8),
    backgroundColor: '#F0F0F0',
  },
  itemDetails: {
    flex: 1,
    marginLeft: scale(12),
  },
  itemName: {
    fontSize: scale(14),
    color: '#333',
  },
  priceContainer: {
    alignItems: 'flex-end',
    marginTop: scale(12),
    paddingTop: scale(12),
    borderTopWidth: 1,
    borderTopColor: '#F0F0F0',
  },
  priceText: {
    fontSize: scale(16),
    fontWeight: '500',
    color: '#333',
  },
  deliveryInfoContainer: {
    padding: scale(16),
    borderBottomWidth: 1,
    borderBottomColor: '#F0F0F0',
  },
  deliveryInfoItem: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: scale(8),
  },
  deliveryInfoText: {
    fontSize: scale(14),
    color: '#666',
    marginLeft: scale(8),
  },
});

export default OrderTrackingScreen; 